package com.xiashitech.agent.instrumentation.async.boot;

import io.opentelemetry.javaagent.shaded.instrumentation.api.instrumenter.Instrumenter;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Context;

import javax.annotation.Nullable;

/**
 * 异步响应回调
 * @author zhoayk
 */
abstract public class AsyncCallback<REQUEST, RESPONSE> {

    private Instrumenter<REQUEST, RESPONSE> instrumenter;

    private REQUEST request;

    public AsyncCallback(Instrumenter<REQUEST, RESPONSE> instrumenter, REQUEST request) {
        this.instrumenter = instrumenter;
        this.request = request;
    }

    @Nullable
    abstract protected RESPONSE buildResponse(REQUEST request, Object rtn);

    public Context callback(Object rtn, Context context) {
        RESPONSE resp = buildResponse(request, rtn);
        if (resp != null && instrumenter.shouldStart(context, request)) {
            context = instrumenter.start(context, request);
            instrumenter.end(context, request, resp, null);
            return context;
        }
        return null;
    }

}
